package com.ck.controller.student;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Chapter;
import com.ck.domain.Panduan;
import com.ck.service.QuestionService;

public class ExercisePanduanSettingController extends SimpleFormController {
	
	private QuestionService questionService;

	public void setQuestionService(QuestionService questionService) {
		this.questionService = questionService;
	}

	//公共变量，用于表单回显
	private List<Chapter> chapterList = null;
	
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		Map model = new HashMap();
		chapterList = questionService.gainChapterList();
		model.put("chapterList", chapterList);
		return model;
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		Panduan panduan = (Panduan) command;
		Map model = errors.getModel();
		
		//后台校验
		boolean flag = true;
		Integer chapterID = panduan.getChapter();
		Integer difficulty = panduan.getDifficulty();
		
		if( chapterID == 0){
			model.put("error_chapterID", "请选择章节");
			flag = false;
		}
		
		if( difficulty == 0){
			model.put("error_difficulty", "请选择难度");
			flag = false;
		}
		
		//校验不通过
        if(!flag){
        	model.put("chapterID", chapterID);
        	model.put("difficulty", difficulty);
        	model.put("chapterList", chapterList);
			return new ModelAndView(getFormView(), model);
		}
		
        List<Panduan> panduanList = questionService.gainPanduanForExercise(panduan, model);
        
        if( panduanList == null){
	        model.put("chapterID", chapterID);
	    	model.put("difficulty", difficulty);
			model.put("chapterList", chapterList);
			return new ModelAndView(getFormView(), model);
        }else{
        	String chapterName = questionService.gainChapter(chapterID).getName();
        	
        	model.put("chapterID", chapterID);
        	model.put("difficulty", difficulty);
        	model.put("chapterName", chapterName);
        	model.put("panduanList", panduanList);
        	return new ModelAndView(getSuccessView(), model);
        }
	}
}
